package solutions.ferpa.ztest.rest.action;

import br.com.telescope.adsrt.lib.BaseRuntime;
import br.com.telescope.sql.Filter;
import solutions.ferpa.ztest.ent.EntPlanoExecucao;
import solutions.ferpa.ztest.rest.RestService;
import solutions.ferpa.ztest.rest.model.AssayPlan;
import solutions.ferpa.ztest.rest.model.def.AssayPlanStatus;
import solutions.ferpa.ztest.rest.model.res.AssayPlanSearchRQ;
import solutions.ferpa.ztest.rest.model.res.AssayPlanSearchRS;
import solutions.ferpa.ztest.rest.model.res.AssayRequestSearchRS;

import java.util.ArrayList;

@RestAction(action = "assayPlanSearch", rqType = AssayPlanSearchRQ.class, rsType = AssayRequestSearchRS.class)
public class AssayPlanSearch extends RestService<AssayPlanSearchRQ, AssayPlanSearchRS> {

    public AssayPlanSearch(BaseRuntime ctx) {
        super(ctx);
    }

    @Override
    public AssayPlanSearchRS call() throws Exception {
        AssayPlanSearchRQ rq = bindRequest(AssayPlanSearchRQ.class);
        AssayPlanSearchRS rs = new AssayPlanSearchRS();
        EntPlanoExecucao planoExecucao = new EntPlanoExecucao(ctx);
        Filter filter = new Filter();
        boolean hasFilter = false;

        if (rq.getId() != null) {
            filter.equal(planoExecucao.getId(), rq.getId());
            hasFilter = true;
        }

        if (rq.getName() != null && ! rq.getName().isEmpty()) {
            filter.like(planoExecucao.getNome(), rq.getName());
            hasFilter = true;
        }

        if (rq.getStatus() != null) {
            filter.equal(planoExecucao.getSituacao(), rq.getStatus().getAchronym());
            hasFilter = true;
        }

        if (hasFilter) planoExecucao.filterBy(filter);

        while (planoExecucao.next()) {
            AssayPlan assayPlan = new AssayPlan();
            assayPlan.setName(planoExecucao.valueOfNome());
            assayPlan.setId(planoExecucao.valueOfId());
            if (planoExecucao.valueOfSituacao().equals(AssayPlanStatus.APPOROVED.getAchronym())) {
                assayPlan.setStatus(AssayPlanStatus.APPOROVED);
            } else if (planoExecucao.valueOfSituacao().equals(AssayPlanStatus.DEPRECATED.getAchronym())) {
                assayPlan.setStatus(AssayPlanStatus.DEPRECATED);
            } else {
                assayPlan.setStatus(AssayPlanStatus.PREPARATION);
            }

            if (rs.getResource() == null) {
                rs.setResource(new ArrayList<AssayPlan>());
            }

            rs.getResource().add(assayPlan);
        }

        planoExecucao.close();

        return rs;
    }
}